/* eslint-disable no-restricted-syntax */
import { messages } from "share/common";
import React from "react";
import { connect } from "react-redux";
import {
  Form,
  Popover,
  Input,
  Switch as Radio,
  Button,
  Icon,
  Select,
  message,
  Spin,
  Tooltip,
  InputNumber,
} from "antd";
import config from "config";
import httpFetch from "share/httpFetch";
import contractService from "containers/setting/contract-type-define/contract-type-define.service";
import "styles/receipt-type-setting/contract-type-define/new-contract-type.scss";
import DateRangePicker from "components/date-range-picker";
import ResizeTable from "components/resize-table";
import ListSelector from "components/list-selector";
import SelectDepartment from "components/template/select-department";
import service from "./service";
import { classifyTypeOptions } from "./config";
import errorMessage from "share/errorMessage";

const FormItem = Form.Item;
const { Option } = Select;

class ExpenseAmountRuleNewForm extends React.Component {
  constructor(props) {
    super(props);
    this.init(props);
  }

  componentWillReceiveProps(nextprops) {
    if (nextprops.params.show && !this.props.params.show) {
      this.props.form.resetFields();
      this.setState({
        selectedList: [],
      });
    }
  }

  init = (props) => {
    const { classifyType, cycle, quatoId } = props.params;
    const currentClassifyType =
      classifyTypeOptions.find((item) => item.value === classifyType) || {};
    // console.log({ currentClassifyType, "props.params": props.params });
    const columns = [
      {
        title: "序号",
        dataIndex: "index",
        render: (text, record, index) => (
          <Popover placement="topLeft" content={index + 1}>
            {index + 1}
          </Popover>
        ),
      },
      {
        title: currentClassifyType.title,
        dataIndex: currentClassifyType.nameKey,
        render: (text, record, index) => (
          <Popover placement="topLeft" content={text}>
            {text}
          </Popover>
        ),
      },
      {
        title: "操作",
        dataIndex: "operation",
        render: (text, record, index) => (
          <div>
            <span>
              <a onClick={() => this.handleDeleteRule(record)}>删除</a>
            </span>
          </div>
        ),
      },
    ];

    this.state = {
      showListSelector: false,
      listType: currentClassifyType.listType,
      currentClassifyType,
      loading: false,
      fetching: false,
      isEnabled: true,
      setOfBooksOptions: [],
      contractCategory: [],
      data: {},
      formTypeOptions: [],
      radioValue: "all",
      showSelectEmployeeGroup: false,
      chosenEmployeeIDs: [],
      editTag: false,
      // 适用人员
      applyEmployee: "BASIS_01",
      departmentOrUserGroupIdList: [],
      permissions: {
        type: "all",
        values: [],
      },
      selectLabel: currentClassifyType.selectLabel,
      selectedList: [],
      selectedIdList: [],
      columns,
    };
  };

  handleDeleteRule = (record) => {
    this.setState({
      selectedList: this.state.selectedList.filter(
        (item) => item.id !== record.id
      ),
    });
  };

  // 新建保存
  handleSave = (e) => {
    e.preventDefault();
    this.props.form.validateFieldsAndScroll(async (err, values) => {
      if (err) return;
      const { dateRange } = values;
      const dateRangeParams = {};

      if (Array.isArray(dateRange)) {
        if (dateRange[0]) {
          dateRangeParams.startTime = dateRange[0].format("YYYY-MM-DD");
        } else {
          message.error('生效时间段的起始日期是必填项');
          return
          // throw new Error('生效时间段的起始日期是必填项'); 
        }
        if (dateRange[1]) {
          dateRangeParams.endTime = dateRange[1].format("YYYY-MM-DD");
        }
      } else {
        message.error('生效时间段的起始日期是必填项');
        return
      }

      const quatoDetailList = this.state.selectedList.map((item) => ({
        quatoId: this.props.params.quatoId,
        pkId: item[this.state.currentClassifyType.pkIdKey],
        amount: values.amount,
        isControl: true,
        ...dateRangeParams,
      }));

      try {
        const res = await service.saveDetailList(quatoDetailList);
        if (res.status === 200) {
          this.props.close(true);
        } else {
          throw res;
        }
      } catch (e) {
        if (e.response) {
          errorMessage(e.response);
          return;
        }
        message.error(e.message);
      }
    });
  };

  // 取消
  handleCancel = () => {
    this.setState({ selectedList: [] });
    this.props.form.resetFields();
    this.props.close();
  };

  handleSelect = () => {
    this.setState({
      showListSelector: true,
    });
  };

  handleListCancel = () => {
    this.setState({
      showListSelector: false,
    });
  };

  handleListOk = (data) => {
    const { result } = data;
    const nextSelectedList = this.state.selectedList.slice();
    // console.log({ result });
    for (const item of result) {
      if (!nextSelectedList.some((value) => value.id === item.id)) {
        nextSelectedList.push(item);
      }
    }
    const selectedIdList = nextSelectedList.map((item) => item.id);
    // console.log({ nextSelectedList });

    this.setState({
      selectedIdList,
      selectedList: nextSelectedList,
      showListSelector: false,
    });
  };

  render() {
    const { getFieldDecorator } = this.props.form;
    const {
      loading,
      setOfBooksOptions,
      contractCategory,
      permissions,
      data,
      formTypeOptions,
      fetching,
      showSelectEmployeeGroup,
      chosenEmployeeIDs,
    } = this.state;
    const formItemLayout = {
      labelCol: { span: 8 },
      wrapperCol: { span: 10, offset: 1 },
    };

    return (
      <div className="new-contract-type">
        <Form onSubmit={this.handleSave}>
          <FormItem {...formItemLayout} label="额度">
            {getFieldDecorator("amount", {
              rules: [
                {
                  required: true,
                  message: messages("common.please.input"),
                },
              ],
            })(
              <InputNumber
                placeholder={messages("common.please.enter")}
                step="0.01"
              />
            )}
          </FormItem>

          <FormItem {...formItemLayout} label="生效时间段">
            {getFieldDecorator("dateRange", {
              rules: [
                {
                  required: false,
                  message: messages("common.please.select"),
                },
              ],
            })(<DateRangePicker />)}
          </FormItem>

          {/* <FormItem {...formItemLayout} label={"是否管控"}>
            {getFieldDecorator("isControl", {
              valuePropName: "checked",
              rules: [
                {
                  required: true,
                },
              ],
              initialValue: false,
            })(<Radio />)}
          </FormItem> */}
          <div className="table-header">
            <div className="table-header-buttons">
              <Button onClick={this.handleSelect} type="primary">
                {this.state.selectLabel}
              </Button>
            </div>
          </div>
          <ResizeTable
            rowKey="adCode"
            loading={loading}
            dataSource={this.state.selectedList}
            columns={this.state.columns}
            pagination={false}
            size="middle"
            bordered
          />

          <div className="slide-footer">
            <Button type="primary" htmlType="submit" loading={loading}>
              {messages("common.save")}
            </Button>
            <Button onClick={this.handleCancel}>
              {messages("common.cancel")}
            </Button>
          </div>
        </Form>

        <ListSelector
          visible={this.state.showListSelector}
          type={this.state.listType}
          onCancel={this.handleListCancel}
          onOk={this.handleListOk}
          selectedData={this.state.selectedList}
          extraParams={this.state.currentClassifyType.listExtraParams || {}}
          single={false}
          labelKey={this.state.selectLabel === '选择车辆' ? 'carNumber' : 'fullName'}
          valueKey={this.state.selectLabel === '选择车辆' ? 'carNumber' : 'userOID'}
          hidePagination={false}
          showDetail={true}
          showArrow={false}
          // maxNum={maxNum}
          // selectorItem={this.state.selectorItem}
          // method={this.props.method}
          // extraBottom={this.props.extraBottom}
          // modalRef={this.props.modalRef}
          // noValueError={noValueError}
        />
      </div>
    );
  }
}

ExpenseAmountRuleNewForm.contextTypes = {
  router: React.PropTypes.object,
};

function mapStateToProps(state) {
  return {
    main: state.main,
  };
}

export default connect(mapStateToProps, null, null, { withRef: true })(
  Form.create()(ExpenseAmountRuleNewForm)
);
